﻿using Microsoft.AspNetCore.Hosting;
using System.Collections.Concurrent;
using System.Threading;

namespace DotNetStar.TheKing.Infrastructure
{
    /// <summary>
    /// 表示消息的调度器。
    /// </summary>
    public class NotificationSchedular
    {
        /// <summary>
        /// 消息队列
        /// </summary>
        private static ConcurrentQueue<INotification> _messageQueue;
        
        /// <summary>
        /// 启动发送验证码的调度器
        /// </summary>
        public void Start()
        {
            var thread = new Thread(new ThreadStart(this.Send))
            {
                IsBackground = true
            };
            thread.Start();
        }

        private readonly IHostingEnvironment _environment;
        /// <summary>
        /// 初始化 <see cref="NotificationSchedular"/> 类的新实例。
        /// </summary>
        /// <param name="environment">环境对象。</param>
        public NotificationSchedular(IHostingEnvironment environment)
        {
            this._environment = environment;
            _messageQueue = new ConcurrentQueue<INotification>();
        }

        public void CreateNotification(INotification model)
        {
            _messageQueue.Enqueue(model);
        }

        /// <summary>
        /// 这个由任务计划进行调度
        /// </summary>
        void Send()
        {
            while (true)
            {
                if (_messageQueue.TryDequeue(out var value))
                {
                    value.Send();
                }
                Thread.Sleep(5000);
            }
        }
    }
}
